'use strict';

const Service = require('egg').Service;

class NoticeService extends Service {
    /**
     * 查询列表
     *
     * @param {String} title @default null -公告名称
     * @param {Boolean} sort @default -1 -排序
     * @param {Number} page @default 1 -当前页
     * @param {Number} currentPage @default 10 -返回条数
     * @param {String} select @default null -要显示的key
     */
    async find({ title = '', sort = -1, page = 1, currentPage = 10 } = {}, select = null) {
        const { ctx } = this;
        const userpopulate = 'headImg role username name';

        const res = await ctx.model.Notice
            .find()
            .regex('title', new RegExp(title, 'i'))
            .sort({ createAt: sort })
            .skip((Number(page) - 1) * Number(currentPage))
            .limit(Number(currentPage))
            .populate('auth', userpopulate)
            .select(select);
        const count = await ctx.model.Notice.find().regex('title', new RegExp(title, 'i')).count();
        return {
            count,
            page,
            list: res
        };
    }

    /**
     * 新增
     *
     * @param {String} title - 标题
     * @param {String} content - 内容
     */
    async create({ title, content } = {}) {
        const { ctx } = this;
        return await ctx.model.Notice.create({
            title,
            content,
            auth: ctx.state.user._id
        });
    }

    /**
     * 修改
     *
     * @param {String} id -id
     * @param {Object} payload -修改条件
     */
    async update(id, payload = {}) {
        const { ctx } = this;
        const notice = await ctx.model.Notice.findById(id);
        if (!notice || notice.delete) {
            ctx.throw(404, '公告不存在或已被删除');
        }
        // 权限验证
        await ctx.powerValidate(notice.auth._id);

        payload.updateAt = Date.now();
        return await ctx.model.Notice.findByIdAndUpdate(id, payload);
    }

    /**
     * 删除
     *
     * @param {String} ids -id
     */
    async destroy(id) {
        const { ctx } = this;
        const notice = await ctx.model.Notice.findById(id);
        if (!notice || notice.delete) {
            ctx.throw(404, '公告不存在或已被删除');
        }
        // 权限验证
        await ctx.powerValidate();

        return await ctx.model.Notice.findByIdAndRemove(id);
    }
}

module.exports = NoticeService;
